package com.android.aiod.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.aiod.R;
import com.android.aiod.bean.ConfigInfo;
import com.android.aiod.bean.SerailDataInfo_Base;
import com.android.aiod.event.Event_ReceiveData;
import com.android.aiod.manager.ConfigManager;
import com.android.aiod.manager.DataParsingManager;
import com.android.aiod.manager.MediaPlayManager;
import com.android.aiod.manager.SerialConnectManager;
import com.android.aiod.manager.VoiceManager;
import com.android.aiod.ui.view.MyJzvdStd;
import com.android.aiod.utils.AudioUtil;
import com.android.aiod.utils.LogUtil;
import com.android.baselibrary.interface_.CommCallBack;
import com.android.baselibrary.tool.AndPermisionUtil;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.util.Util;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.hjq.permissions.Permission;
import com.licheedev.hwutils.ByteUtil;
import com.wangpm.enteranimation.EnterAnimLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.Jzvd;

/**
 * 首页
 */
public class HomeActivity extends BaseActivity {

    @BindView(R.id.jz_video)
    MyJzvdStd jz_video;
    @BindView(R.id.iv_img)
    ImageView iv_img;
    @BindView(R.id.anim_view)
    EnterAnimLayout anim_view;
    @BindView(R.id.ll_text_content)
    LinearLayout ll_text_content;
    @BindView(R.id.tv_log)
    TextView tv_log;
    @BindView(R.id.ll_log)
    LinearLayout ll_log;


    VoiceManager voiceManager;      //语音播放管理类
    MediaPlayManager mediaManager;    //媒体播放管理类
    SerialConnectManager serialConnectManager;   //串口连接管理类
    DataParsingManager dataParsingManager;
    Timer timer;
    TimerTask timerTask;
    Handler handler=new Handler();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    protected boolean isRegistEventbus() {
        return true;
    }

    @Override
    protected void initView() {
        startProgressTimer();
    }

    public void startProgressTimer() {
        cancelProgressTimer();
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
//                        CommToast.showToast(mContext,"发送广播");
                        Intent intent = new Intent("comzc.zclcdon");
                        sendBroadcast(intent);
                    }
                });
            }
        };
        timer.schedule(timerTask, 0, 1000*60*10);
    }

    public void cancelProgressTimer() {
        if (timer != null) {
            timer.cancel();
            timer =null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask=null;
        }
    }

    @Override
    protected void initData() {
        AndPermisionUtil.requstPermision(mContext, new AndPermisionUtil.PermisionCallBack() {
            @Override
            public void onGranted() {
                //初始化配置信息
                ConfigManager.instance();
                //初始化媒体
                mediaManager = new MediaPlayManager(mContext, jz_video, iv_img, anim_view);
                //初始化语音
                voiceManager = new VoiceManager(mContext);
                initText();
            }

            @Override
            public void onDenied() {
                CommToast.showToast(mContext, "没有文件权限，无法读取本地文件");
            }
        }, Permission.Group.STORAGE);

        //初始化串口
        serialConnectManager = new SerialConnectManager(mContext);
        serialConnectManager.connectDefault();
        dataParsingManager = new DataParsingManager(new CommCallBack() {
            @Override
            public void onResult(Object obj) {
                byte[] bytes_final = (byte[]) obj;
                receiveFinalData(bytes_final);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelProgressTimer();
    }

    private void initText() {
        ConfigInfo configInfo = ConfigManager.instance().configInfo;
        int text_padding_left = Util.dip2px(mContext, configInfo.text_padding_left);
        int text_padding_right = Util.dip2px(mContext, configInfo.text_padding_right);
        int text_padding_top = Util.dip2px(mContext, configInfo.text_padding_top);
        int text_padding_bottom = Util.dip2px(mContext, configInfo.text_padding_bottom);

        ll_text_content.setPadding(text_padding_left, text_padding_top, text_padding_right, text_padding_bottom);
        ll_text_content.setBackgroundColor(Color.parseColor(configInfo.text_bg_color));
        //文字位置
//        if (configInfo.text_position == 1) {
//            RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) ll_text_content.getLayoutParams();
//            params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//            ll_text_content.setLayoutParams(params1);
//        }

        for (int i = 0; i < 6; i++) {
            TextView textView = new TextView(mContext);
            initFont(textView);
            if (i != 0) {
                //加边距
                LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params1.topMargin = Util.dip2px(mContext, configInfo.text_lineSpacing);
                textView.setLayoutParams(params1);
            }
            ll_text_content.addView(textView);
        }

//        CommToast.showToast(mContext,"configInfo.showLog:"+ configInfo.showLog);
//        if (configInfo.showLog == 1) {
//            ll_log.setVisibility(View.VISIBLE);
//        }
//        ll_log.setVisibility(View.VISIBLE);
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }


    @OnClick({R.id.tv_test1, R.id.tv_test2, R.id.tv_test3, R.id.tv_clear, R.id.tv_copy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_test1:  //测试文字
//                StartActivity(SettingActivity.class);
                Event_ReceiveData event1 = new Event_ReceiveData();
                byte[] byte_source1 = ByteUtil.hexStr2bytes(Event_ReceiveData.data_text.replace(" ", ""));
                event1.received = byte_source1;
                EventBus.getDefault().post(event1);
                break;
            case R.id.tv_test2:  //测试语音
                Event_ReceiveData event2 = new Event_ReceiveData();
                byte[] byte_source2 = ByteUtil.hexStr2bytes(Event_ReceiveData.data_voice.replace(" ", ""));
                event2.received = byte_source2;
                EventBus.getDefault().post(event2);
                break;
            case R.id.tv_test3:  //测试清除文字
                Event_ReceiveData event3 = new Event_ReceiveData();
                byte[] byte_source3 = ByteUtil.hexStr2bytes(Event_ReceiveData.data_clear.replace(" ", ""));
                event3.received = byte_source3;
                EventBus.getDefault().post(event3);
                break;
            case R.id.tv_clear:
                tv_log.setText("");
                System.gc();
                break;
            case R.id.tv_copy:
                Util.copy(mContext, tv_log.getText().toString(), true);
                break;
        }
    }

    //收到数据
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event_ReceiveData event) {
        receiveFinalData(event.received);
//        dataParsingManager.ReceiveData(event.received);
    }

    public void receiveFinalData(byte[] data) {
        SerailDataInfo_Base dataInfo = null;
        try {
            //解析指令
            dataInfo = DataParsingManager.parsingData(data, tv_log);
            if (dataInfo.error == 0) {
                //执行指令
                doCMD(dataInfo);
            } else {
//                String err = "";
//                if (dataInfo.error == (byte) 0x01) {
//                    err = "CRC校验不对";
//                } else if (dataInfo.error == (byte) 0x02) {
//                    err = "指令无效";
//                } else if (dataInfo.error == (byte) 0x03) {
//                    err = "data长度不对";
//                } else if (dataInfo.error == (byte) 0x04) {
//                    err = "序列号不对";
//                }
//                tv_log.setText(tv_log.getText() + "解析失败：" + err + "\n");
            }
            switch (dataInfo.getCMD_Str()) {
                case "A3":      //清除文字
                    LogUtil.writerlog("清屏：" + ConvertUtils.bytes2HexString(data));
                    break;
                case "A4":      //展示文字
                    LogUtil.writerlog("费显：" + ConvertUtils.bytes2HexString(data));
                    break;
                case "A6":      //播放语音
                    LogUtil.writerlog("语音：" + ConvertUtils.bytes2HexString(data));
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            //返回指令
//            String cmd = dataInfo.getCMD_Str();
//            if ("A3".equals(cmd) || "A4".equals(cmd) || "A6".equals(cmd)) {
//                if (dataInfo.error == 0) {
//                    serialConnectManager.sendData(DataParsingManager.createReturnData(dataInfo, tv_log));
//                }
//            }
        }
        //最后清理内存
        System.gc();
    }

    //执行串口指令
    private void doCMD(SerailDataInfo_Base dataInfo) {
        switch (dataInfo.getCMD_Str()) {
            case "A3":      //清除文字
                ll_text_content.setVisibility(View.GONE);
//                CommToast.showToast(mContext, "清除文字");
//                tv_log.setText(tv_log.getText() + "解析成功，清除文字\n");
                break;
            case "A4":      //展示文字
                showText(dataInfo);
                ll_text_content.setVisibility(View.VISIBLE);
//                CommToast.showToast(mContext, "展示文字");
//                tv_log.setText(tv_log.getText() + "解析成功，展示文字\n");
                break;
            case "A6":      //播放语音
                voiceManager.play(dataInfo.getCodeStr_TextVoice());
                AudioUtil.getInstance(mContext).setMediaVolume(dataInfo.getMediaVolume());
//                CommToast.showToast(mContext, "播放语音");
//                tv_log.setText(tv_log.getText() + "解析成功，播放语音\n");
                break;
        }
    }

    //展示文字
    private void showText(SerailDataInfo_Base dataInfo) {
        try {
            List<String> textList = dataInfo.getCodeStr_TextList();
            String color = dataInfo.getTextColor();
            float alpha = dataInfo.getAlpha();
            //设置文本内容
            for (int i = 0; i < 6; i++) {
                TextView textView = (TextView) ll_text_content.getChildAt(i);
                String text = textList.get(i).trim();
                textView.setText(text);
                textView.setAlpha(alpha);
                if (!TextUtils.isEmpty(color)) {
                    textView.setTextColor(Color.parseColor(color));
                }
                textView = null;
            }
            textList = null;
//            //设置屏幕亮度
//            int light = (int) (alpha * 255);
//            BrightnessUtils.setBrightness(light);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //初始化文字信息
    private void initFont(TextView tv_text) {
        ConfigInfo configInfo = ConfigManager.instance().configInfo;
        //字体
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Typeface iconfont;
                if (configInfo.text_typeface == 1) {
                    iconfont = Typeface.createFromAsset(mContext.getAssets(), "simhei.ttf");
                } else if (configInfo.text_typeface == 2) {
                    iconfont = Typeface.createFromAsset(mContext.getAssets(), "simkai.ttf");
                } else {
                    iconfont = Typeface.DEFAULT;
                }
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_text.setTypeface(iconfont, Typeface.NORMAL);
                        if (configInfo.text_bold == 1 && configInfo.text_italics == 1) {
                            tv_text.setTypeface(iconfont, Typeface.BOLD_ITALIC);
                        } else if (configInfo.text_italics == 1) {
                            tv_text.setTypeface(iconfont, Typeface.ITALIC);
                        } else if (configInfo.text_bold == 1) {
                            tv_text.setTypeface(iconfont, Typeface.BOLD);
                        } else {
                            tv_text.setTypeface(iconfont, Typeface.NORMAL);
                        }

                        tv_text.setTextSize(configInfo.text_size);
                        tv_text.setTextColor(Color.parseColor(configInfo.text_color));
                        tv_text.getPaint().setAntiAlias(true);//抗锯齿

                        //下划线
                        int flag = 0;
                        if (configInfo.text_underline == 1) {
                            flag = Paint.UNDERLINE_TEXT_FLAG;
                        }
                        tv_text.getPaint().setFlags(flag);
                        //行间距
                        tv_text.setLineSpacing(Util.dip2px(mContext, configInfo.text_lineSpacing), 1);
                    }
                });
            }
        }).start();

    }


}
